﻿/*
 * Copyright (C) 2012, Jesus Requejo <jesus.requejo@gmail.com> 
 * Licensed under Microsoft Public License (Ms-PL)
 * http://www.microsoft.com/en-us/openness/licenses.aspx#MPL
*/

namespace Infrastructure {

   using System;
   using System.IO;
   using System.Net;
   using System.Net.Sockets;

   public static class ServiceMessenger {

      public static readonly int PORT = 52384;
      public static readonly string IP = "127.0.0.1";

      public static string SendMessageToServiceAndReturnResponse(string request) {

         IPAddress ipAddress = IPAddress.Parse(IP);
         IPEndPoint localEndPoint = new IPEndPoint(ipAddress, PORT);
         Socket soc = new Socket(localEndPoint.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
         soc.Connect(localEndPoint);

         NetworkStream netStream = new NetworkStream(soc, FileAccess.ReadWrite, false);
         var sw = new StreamWriter(netStream);
         
         sw.WriteLine(request);
         sw.Flush();

         var sr = new StreamReader(netStream);
         var response = sr.ReadLine();

         sr.Dispose();
         sw.Dispose();

         return response;
      }

      public static string ReadRequestFromClientAndSendResponse(
         Socket clientSocket, Func<string, string> requestProcessor) 
      {
         NetworkStream netStream = new NetworkStream(clientSocket);
         var sr = new StreamReader(netStream);
         var sw = new StreamWriter(netStream);

         var request = sr.ReadLine();
         string response = requestProcessor(request);

         sw.WriteLine(response);
         sw.Flush();

         sr.Dispose();
         sw.Dispose();

         return response;
      }      
   }
}
